package com.example.controller;


import com.example.dao.TestQuestionCrudRepository;
import com.example.dao.UserCrudRepository;
import com.example.pojo.TestQuestion;
import com.example.pojo.PageBean;
import com.example.pojo.User;
import com.example.tools.JwtUtils;
import com.example.tools.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.*;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/testQuestion")
@Slf4j
public class TestQuestionController {
    @Autowired
    private TestQuestionCrudRepository testQuestionCrudRepository;
    @Autowired
    private UserCrudRepository userCrudRepository;

    @PostMapping("/addTestQuestion")
    public Result add(@RequestBody TestQuestion testQuestion, @RequestHeader("token") String token) {
        Integer id = JwtUtils.parseJWT(token).get("id", Integer.class);
        User user = userCrudRepository.findById(id).get();
        testQuestion.setAgencyId(user.getAgencyId());
        TestQuestion save = testQuestionCrudRepository.save(testQuestion);
        return Result.success(save);
    }

    @DeleteMapping("/deleteTestQuestion")
    public Result delete(@RequestBody List<Integer> ids, @RequestHeader("token") String token) {
        Integer id = JwtUtils.parseJWT(token).get("id", Integer.class);
        User user = userCrudRepository.findById(id).get();
        String result="";
        for (Integer testQuestionId : ids) {
            TestQuestion testQuestion = testQuestionCrudRepository.findById(testQuestionId).get();
            if(testQuestion.getAgencyId()==user.getAgencyId()){
                testQuestionCrudRepository.deleteById(testQuestionId);
            }else {
                result =result+testQuestionId+" ";
            }
        }
        if(result.equals("")){
            return Result.success("删除成功");
        }
        return Result.error("编号为:"+result+"的试题为共享试题,无权删除");
    }

    @PostMapping("/updateTestQuestion")
    public Result update(@RequestBody TestQuestion testQuestion,@RequestHeader("token") String token) {
        Integer id = JwtUtils.parseJWT(token).get("id", Integer.class);
        User user = userCrudRepository.findById(id).get();
        //机构管理员没有权限操作超级管理员上传的文件
        if(user.getRole().equals("机构管理员")&&testQuestion.getAgencyId()==0){
            return Result.error("没有权限");
        }
        TestQuestion save = testQuestionCrudRepository.save(testQuestion);
        return Result.success(save);
    }

    @PostMapping("/getAllTestQuestion")
    public Result getAllTestQuestion(@RequestBody TestQuestion testQuestion,
                                     @RequestParam(defaultValue = "1") Integer page,
                                     @RequestParam(defaultValue = "10") Integer pageSize,
                                     @RequestHeader("token") String token) {
        Integer id = JwtUtils.parseJWT(token).get("id", Integer.class);
        User user = userCrudRepository.findById(id).get();
        log.info("testQuestion:{}", testQuestion);
        Pageable pageable = PageRequest.of(page - 1, pageSize, Sort.Direction.ASC, "id");

        Page<TestQuestion> coursePage = testQuestionCrudRepository.findAll(new Specification<TestQuestion>() {
            @Override
            public Predicate toPredicate(Root<TestQuestion> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                //获取条件对象
                Predicate predicate = cb.conjunction();
                //判断用户对象
                if (testQuestion != null) {
                    // 根据 student 的属性添加查询条件
                    if (testQuestion.getId() != null) {
                        predicate.getExpressions().add(cb.equal(root.get("id"), testQuestion.getId()));
                    }
                    if (testQuestion.getType() != null) {
                        predicate.getExpressions().add(cb.equal(root.get("type"), testQuestion.getType()));
                    }
                    if (testQuestion.getQuestion() != null) {
                        predicate.getExpressions().add(cb.equal(root.get("question"), testQuestion.getQuestion()));
                    }
                    if (user.getAgencyId() != null) {
                        //查自己的题库以及超级管理员发的共享试题
                        predicate.getExpressions().add(cb.or(
                                cb.equal(root.get("agencyId"), user.getAgencyId()),
                                cb.equal(root.get("agencyId"), 0)
                        ));
                    }

                }
                return predicate;
            }
        }, pageable);
        List<TestQuestion> TestQuestions = coursePage.getContent();
        long elements = coursePage.getTotalElements();
        return Result.success(new PageBean(elements, TestQuestions));
    }

    @GetMapping("/getTestQuestionList")
    public Result getTestQuestionList() {
        Iterable<TestQuestion> all = testQuestionCrudRepository.findAll();
        List<TestQuestion> TestQuestionList = new ArrayList<>();
        for (TestQuestion testQuestion : all) {
            TestQuestionList.add(testQuestion);
        }
        return Result.success(TestQuestionList);
    }

}
